package com.comac.tasks.manager.app.command.query;

import com.alibaba.fastjson.JSON;
import com.comac.tasks.manager.app.common.enums.DealTypeEnum;
import com.comac.tasks.manager.app.domain.gateway.TasksManagerGateway;
import com.comac.tasks.manager.app.dto.PageResponse;
import com.comac.tasks.manager.app.dto.TasksManagerQry;
import com.comac.tasks.manager.app.dto.TasksManagerVO;
import com.comac.tasks.manager.app.gatewayimpl.database.dataobject.TasksManagerTodoDO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author wfb
 */
@Component
public class TasksManagerListQryExe {

    @Autowired
    private TasksManagerGateway tasksManagerGateway;

    public PageResponse<TasksManagerVO> execute(TasksManagerQry tasksManagerQry) {
        PageResponse<TasksManagerVO> PageResponseVo = new PageResponse<>();
        List<TasksManagerVO> list = new ArrayList<>();
        //分页代办等条件查询
        List<String> statusList = Arrays.asList("END", "CANCEL", "ROLLBACK", "REJECT","RECALL");
        PageResponse<TasksManagerTodoDO> dtoPageResponse = tasksManagerGateway.selectPage(tasksManagerQry);
        if (!dtoPageResponse.getData().isEmpty()) {
            dtoPageResponse.getData().stream().forEach(e -> {
                TasksManagerVO tasksManagerVO = new TasksManagerVO();
                BeanUtils.copyProperties(e, tasksManagerVO);
                tasksManagerVO.setId(e.getId()+"");
                tasksManagerVO.setFieldArea((Map) JSON.parse(e.getFieldArea()));
                String statusType = null;
                if(StringUtils.isNotBlank(e.getStatus())){
                    if(statusList.contains(e.getStatus())||statusList.contains(e.getProcessNodeStatus())){
                         statusType = DealTypeEnum.RECALL.getType();
                    }else{
                         statusType = DealTypeEnum.getType(e.getStatus());
                    }
                }
                tasksManagerVO.setStatus(statusType);
                list.add(tasksManagerVO);
            });
        }
        PageResponseVo.setPageNum(dtoPageResponse.getPageNum());
        PageResponseVo.setPageSize(dtoPageResponse.getPageSize());
        PageResponseVo.setTotalCount(dtoPageResponse.getTotalCount());
        PageResponseVo.setData(list);
        PageResponseVo.setSuccess(Boolean.TRUE);
        return PageResponseVo;
    }
    
}
